package com.keson.door2.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import com.huashi.otg.sdk.HSIDCardInfo;
import com.huashi.otg.sdk.HandlerMsg;
import com.huashi.otg.sdk.HsOtgApi;
import com.huashi.otg.sdk.Test;
import com.keson.door2.MainActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

public class IDCardUtil {
    public static final String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wltlib";// 授权目录
    private static HsOtgApi api;
    private static SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");// 设置日期格式
    private static Context context;
    public static void init(Context context){
        IDCardUtil.context = context;
        copy(context, "base.dat", "base.dat", filepath);
        copy(context, "license.lic", "license.lic", filepath);
        api = new HsOtgApi(h, context);

        new Thread(new Runnable() {
            int ret = api.init();// 因为第一次需要点击授权，所以第一次点击时候的返回是-1所以我利用了广播接受到授权后用handler发送消息
            @Override
            public void run() {
                while (true){
                    if (ret == 1) {
//            statu.setText("ok");
//            sam.setText(api.GetSAMID());
//                        Log.i("读卡器连接","成功");
//                        Log.i("读卡器连接",api.GetSAMID());
                        System.out.println("读卡器连接成功");
                        break;
                    } else {
//            statu.setText("fail");
//                        Log.i("读卡器连接","失败");
                        System.out.println("读卡器连接失败");
                        ret = api.init();
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                HSIDCardInfo ici;
                Message msg;
                while (true) {
                    if(!Cache.hasIdCard){
                        if (api.Authenticate(200, 200) != 1) {
                            msg = Message.obtain();
                            msg.what = HandlerMsg.READ_ERROR;
                            h.sendMessage(msg);
                        } else {
                            Cache.canMoveCard = false;
                            TTSUtil.speek("请勿移动身份证");
                            CameraUtil.stopPreview();
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            ici = new HSIDCardInfo();
                            int code = api.ReadCard(ici, 200, 1300);
                            System.out.println(code);
                            boolean b =  code == 1;
                            System.out.println(b);
                            if (b) {
                                msg = Message.obtain();
                                msg.obj = ici;
                                msg.what = HandlerMsg.READ_SUCCESS;
                                System.out.println("?????????????????");
                                System.out.println(ici.toString());
                                System.out.println(ici.getIDCard());
                                System.out.println("?????????????????");
                                h.sendMessage(msg);
                                TTSUtil.speek("请取回身份证");
                                Cache.canMoveCard = true;
                                CameraUtil.startPreview();
                            }else{
                                TTSUtil.speek("请重新放置身份证");
                                CameraUtil.startPreview();
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                Cache.canMoveCard = true;
                            }
                        }
                    }
                    SystemClock.sleep(300);
                }
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private static Handler h = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 99 || msg.what == 100) {
//                statu.setText((String)msg.obj);
            }
            //第一次授权时候的判断是利用handler判断，授权过后就不用这个判断了
            if (msg.what == HandlerMsg.CONNECT_SUCCESS) {
//                statu.setText("连接成功");
//                sam.setText(api.GetSAMID());
            }
            if (msg.what == HandlerMsg.CONNECT_ERROR) {
//                statu.setText("连接失败");
            }
            if (msg.what == HandlerMsg.READ_ERROR) {
                //cz();
//                statu.setText("卡认证失败");
            }
            if (msg.what == HandlerMsg.READ_SUCCESS) {
//                statu.setText("读卡成功");
                HSIDCardInfo ic = (HSIDCardInfo) msg.obj;
                byte[] fp = new byte[1024];
                fp = ic.getFpDate();
                String m_FristPFInfo = "";
                String m_SecondPFInfo = "";

                if (fp[4] == (byte)0x01) {
                    m_FristPFInfo = String.format("指纹  信息：第一枚指纹注册成功。指位：%s。指纹质量：%d \n", GetFPcode(fp[5]), fp[6]);
                } else {
                    m_FristPFInfo = "身份证无指纹 \n";
                }
                if (fp[512 + 4] == (byte)0x01) {
                    m_SecondPFInfo = String.format("指纹  信息：第二枚指纹注册成功。指位：%s。指纹质量：%d \n", GetFPcode(fp[512 + 5]),
                            fp[512 + 6]);
                } else {
                    m_SecondPFInfo = "身份证无指纹 \n";
                }
                System.out.println("+++++++++++++++++++++++"+ic.getcertType()+"+++++++++++++++++++++");
                if (ic.getcertType() == " ") {
//                    tv_info.setText("证件类型：身份证\n" +
//                            "姓名："+ ic.getPeopleName() + "\n" +
//                            "性别：" + ic.getSex()+ "\n" +
//                            "民族：" + ic.getPeople() + "\n" +
//                            "出生日期："+ df.format(ic.getBirthDay()) + "\n" +
//                            "地址："+ ic.getAddr() + "\n" +
//                            "身份号码：" + ic.getIDCard()+ "\n" +
//                            "签发机关：" + ic.getDepartment() + "\n"+
//                            "有效期限：" + ic.getStrartDate() + "-"+ ic.getEndDate() + "\n" +
//                            m_FristPFInfo + "\n"
//                            + m_SecondPFInfo);
                    System.out.println(ic.getPeopleName());
                    System.out.println(ic.getIDCard());
                    Cache.IDCardInfo.put("name",ic.getPeopleName());
                    Cache.IDCardInfo.put("idNo",ic.getIDCard());
                    Log.i("读卡器","身份证信息读取完毕");
                    System.out.println("----------------------------"+Cache.IDCardInfo.toString());
                    MainActivity.handler.sendMessage(MainActivity.handler.obtainMessage(100));
                } else {
                    if(ic.getcertType() == "J")
                    {
//                        tv_info.setText("证件类型：港澳台居住证（J）\n"+
//                                "姓名：" + ic.getPeopleName() + "\n" +
//                                "性别："+ ic.getSex() + "\n"+
//                                "签发次数：" + ic.getissuesNum() + "\n"+
//                                "通行证号码：" + ic.getPassCheckID() + "\n"+
//                                "出生日期：" + df.format(ic.getBirthDay())+ "\n" +
//                                "地址：" + ic.getAddr() + "\n" +
//                                "身份号码："+ ic.getIDCard() + "\n" +
//                                "签发机关："+ ic.getDepartment() + "\n" +
//                                "有效期限："+ ic.getStrartDate() + "-" + ic.getEndDate() + "\n"
//                                + m_FristPFInfo + "\n" + m_SecondPFInfo);
                    }
                    else{
                        if(ic.getcertType() == "I")
                        {
//                            tv_info.setText("证件类型：外国人永久居留证（I）\n"
//                                    + "英文名称：" + ic.getPeopleName() + "\n"
//                                    + "中文名称：" + ic.getstrChineseName() + "\n"
//                                    + "性别：" + ic.getSex() + "\n"
//                                    + "永久居留证号：" + ic.getIDCard() + "\n"
//                                    + "国籍：" + ic.getstrNationCode() + "\n"
//                                    + "出生日期：" + df.format(ic.getBirthDay())
//                                    + "\n" + "证件版本号：" + ic.getstrCertVer() + "\n"
//                                    + "申请受理机关：" + ic.getDepartment() + "\n"
//                                    + "有效期限："+ ic.getStrartDate() + "-" + ic.getEndDate() + "\n"
//                                    + m_FristPFInfo + "\n" + m_SecondPFInfo);
                        }
                    }

                }
//                Test.test("/mnt/sdcard/test.txt4", ic.toString());
                try {
                    int ret = api.Unpack(filepath, ic.getwltdata());// 照片解码
//                    Test.test("/mnt/sdcard/test3.txt", "解码中");
                    if (ret != 0) {// 读卡失败
                        Log.i("照片解码","失败");
                        return;
                    }
                    FileInputStream fis = new FileInputStream(filepath + "/zp.bmp");
                    Bitmap bmp = BitmapFactory.decodeStream(fis);
                    fis.close();
//                    iv_photo.setImageBitmap(bmp);
                    Cache.hasIdCard = true;
                } catch (FileNotFoundException e) {
                    Toast.makeText(IDCardUtil.context, "头像不存在！", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    Toast.makeText(IDCardUtil.context, "头像读取错误", Toast.LENGTH_SHORT).show();
                }catch (Exception e)
                {
                    Toast.makeText(IDCardUtil.context, "头像解码失败", Toast.LENGTH_SHORT).show();
                }

            }
        };
    };

    private static void copy(Context context, String fileName, String saveName,
                      String savePath) {
        File path = new File(savePath);
        if (!path.exists()) {
            path.mkdir();
        }

        try {
            File e = new File(savePath + "/" + saveName);
            if (e.exists() && e.length() > 0L) {
                Log.i("LU", saveName + "存在了");
                return;
            }

            FileOutputStream fos = new FileOutputStream(e);
            InputStream inputStream = context.getResources().getAssets()
                    .open(fileName);
            byte[] buf = new byte[1024];
            boolean len = false;

            int len1;
            while ((len1 = inputStream.read(buf)) != -1) {
                fos.write(buf, 0, len1);
            }

            fos.close();
            inputStream.close();
        } catch (Exception var11) {
            Log.i("LU", "IO异常");
        }

    }

    private static String GetFPcode(int FPcode) {
        switch (FPcode) {
            case 11:
                return "右手拇指";
            case 12:
                return "右手食指";
            case 13:
                return "右手中指";
            case 14:
                return "右手环指";
            case 15:
                return "右手小指";
            case 16:
                return "左手拇指";
            case 17:
                return "左手食指";
            case 18:
                return "左手中指";
            case 19:
                return "左手环指";
            case 20:
                return "左手小指";
            case 97:
                return "右手不确定指位";
            case 98:
                return "左手不确定指位";
            case 99:
                return "其他不确定指位";
            default:
                return "未知";
        }
    }

    public static void unInit(){
        api.unInit();
    }
}
